<template>
  <div>
    <!-- 面包屑部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主题表格部分 -->
    <el-card>
      <el-button type="primary" @click="addRoles">添加角色</el-button>
      <el-divider></el-divider>
      <el-table :data="RolesList" border stripe style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'rowcenter']"
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="4">
                <el-tag closable @close="deleteTag(scope.row, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[index2 === 0 ? '' : 'bdtop']"
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="5">
                    <el-tag
                      closable
                      @close="deleteTag(scope.row, item2.id)"
                      type="success"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="deleteTag(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column label="角色名称" prop="roleName"> </el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              @click="editRoles(scope.row.id)"
              size="mini"
              type="primary"
              icon="el-icon-edit"
            >
              编辑
            </el-button>
            <el-button
              @click="deleteRoles(scope.row.id)"
              size="mini"
              type="danger"
              icon="el-icon-delete"
            >
              删除
            </el-button>
            <el-button
              @click="assignCompetence(scope.row)"
              size="mini"
              type="warning"
              icon="el-icon-setting"
            >
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 弹出框 -->
    <!-- 添加弹出框 -->
    <el-dialog
      title="添加新的角色"
      @close="resetOne"
      :visible.sync="isAdd"
      width="50%"
    >
      <el-form
        :model="addFrom"
        :close-on-click-modal="false"
        :rules="addFromRules"
        ref="addFromRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAdd = false">取 消</el-button>
        <el-button type="primary" @click="add"> 确 定 </el-button>
      </span>
    </el-dialog>
    <!-- 编辑弹出框 -->
    <el-dialog
      title="修改角色信息"
      @close="resetTwo"
      :visible.sync="isEdit"
      width="50%"
    >
      <el-form
        :model="editFrom"
        :close-on-click-modal="false"
        :rules="editFromRules"
        ref="editFromRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEdit = false">取 消</el-button>
        <el-button type="primary" @click="edit(editFrom.roleId)">
          确 定
        </el-button>
      </span>
    </el-dialog>
    <!-- 权限分配弹出框 -->
    <el-dialog
      @close="closeAssign"
      title="权限分配"
      :visible.sync="isAssign"
      width="50%"
    >
      <el-tree
        show-checkbox
        default-expand-all
        check-on-click-node
        ref="treeRef"
        node-key="id"
        :default-checked-keys="defKey"
        :data="rightList"
        :props="treeProps"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAssign = false">取 消</el-button>
        <el-button type="primary" @click="Assign">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  created() {
    this.getRolesList()
  },
  data() {
    return {
      RolesList: [],
      //权限列表数据
      rightList: [],
      // 树形控件的绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      //控制树形控件展开默认选中
      defKey: [],
      //   需要添加的角色数据
      addFrom: {
        roleName: "",
        roleDesc: ""
      },
      //是否弹出添加框
      isAdd: false,
      //是否弹出编辑框
      isEdit: false,
      //是否弹出删除框
      isDelete: false,
      //是否弹出权限分配框
      isAssign: false,
      //根据id查询角色数据
      editFrom: {},
      // 要分配权限的角色id
      roleid: '',
      //表单规则
      editFromRules: {
        roleName:
          [{ required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur' }],
        roleDesc:
          [{ required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 1, max: 6, message: '长度在1 到 6 个字符', trigger: 'blur' }],
      },
      addFromRules: {
        roleName:
          [{ required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur' }],
        roleDesc:
          [{ required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 1, max: 6, message: '长度在1 到 6 个字符', trigger: 'blur' }],
      }
    }
  },
  methods: {
    //获取角色列表数据
    getRolesList() {
      this.$http.get('http://127.0.0.1:8888/api/private/v1/roles')
        .then((response) => {
          if (response.data.meta.status !== 200) {
            this.$message.error(response.data.meta.msg);
          } else {
            this.RolesList = response.data.data;

          }
        }).catch((error) => console.log(error))
    },
    //添加角色
    addRoles() {
      this.isAdd = true
    },
    add() {
      this.$refs.addFromRef.validate((value) => {
        if (!value) {
          this.$message.error('请完整的输入合法信息！！！')
        } else {
          this.$http.post('http://127.0.0.1:8888/api/private/v1/roles', this.addFrom)
            .then((response) => {
              if (response.data.meta.status !== 201) {
                this.$message.error(response.data.meta.msg);
              } else {
                this.$message.success('用户添加成功');
                this.isAdd = false
                this.getRolesList()
              }
            }).catch((err) => console.log(err))
        }
      })
    },
    // 编辑时获得初始角色信息
    editRoles(id) {
      this.isEdit = true
      this.$http.get(`http://127.0.0.1:8888/api/private/v1/roles/${id}`)
        .then((response) => {
          if (response.data.meta.status !== 200) {
            this.$message.error(response.data.meta.msg);
          } else {
            this.editFrom = response.data.data
          }
        })
        .catch((error) => console.log(error));
    },
    //确认编辑
    edit(id) {
      console.log(id);
      this.$refs.editFromRef.validate((value) => {
        if (!value) {
          this.$message.error('请完整的输入合法信息！！！')
        } else {
          this.$http.put(`http://127.0.0.1:8888/api/private/v1/roles/${id}`,
            { roleName: this.editFrom.roleName, roleDesc: this.editFrom.roleDesc })
            .then((response) => {
              if (response.data.meta.status !== 200) {
                this.$message.error(response.data.meta.msg);
              } else {
                this.$message.success('角色修改成功');
                this.isEdit = false
                this.getRolesList()
              }
            }).catch((err) => console.log(err))
        }
      })
    },
    // 删除角色信息
    deleteRoles(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`http://127.0.0.1:8888/api/private/v1/roles/${id}`)
          .then((response) => {
            if (response.data.meta.status !== 200) {
              this.$message.error(response.data.meta.msg);
            } else {
              this.$message.success(response.data.meta.msg);
              this.getRolesList()
            }
          }).catch((error) => console.log(error))

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });


    },
    //重置表单
    resetOne() {
      this.$refs.addFromRef.resetFields()
    },
    resetTwo() {
      this.$refs.editFromRef.resetFields()
    },
    //删除三级权限标签
    deleteTag(role, rightid) {
      console.log(role.children, rightid);
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`http://127.0.0.1:8888/api/private/v1/roles/${role.id}/rights/${rightid}`)
          .then((response) => {
            console.log(response.data.data);
            if (response.data.meta.status !== 200) {
              this.$message.error(response.data.meta.msg);
            } else {
              this.$message.success(response.data.meta.msg);
              role.children = response.data.data
            }
          }).catch((error) => console.log(error))
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 是否弹出权限分配框
    assignCompetence(role) {
      this.roleid = role.id
      // console.log(role, '1111');
      this.$http.get(`http://127.0.0.1:8888/api/private/v1/rights/tree`)
        .then((response) => {
          if (response.data.meta.status !== 200) {
            this.$message.error(response.data.meta.msg);
          } else {
            this.rightList = response.data.data;
            this.getdefKey(role, this.defKey)
            // console.log(this.defKey, '222');
            // console.log(this.rightList);
          }
        }).catch((error) => console.log(error))
      this.isAssign = true
    },
    // 通过递归获取需要默认选中节点的id
    getdefKey(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      // 遍历每个孩子中是否还有孩子（递归）
      node.children.forEach(item => {
        this.getdefKey(item, arr)//item相当于实参
      })
    },
    // 关闭弹框时清空选中，防止保留
    closeAssign() {
      this.defKey = []
    },
    //确定权限分配
    Assign() {
      const keys = [
        ...this.$refs.treeRef.
          getCheckedKeys(),
        ...this.$refs.treeRef.
          getHalfCheckedKeys()]

      const idstr = keys.join(',')
      console.log(idstr);

      this.$http.post(`http://127.0.0.1:8888/api/private/v1/roles/${this.roleid}/rights`,
        { rids: idstr })
        .then((response) => {
          if (response.data.meta.status !== 200) {
            this.$message.error(response.data.meta.msg);
          } else {
            this.$message.success(response.data.meta.msg);
            this.getRolesList()
            this.isAssign = false
          }
        }).catch((error) => console.log(error))
    }



  }
}
</script>

<style scoped>
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.el-tag {
  margin: 5px;
}
.el-col {
  margin: 7px;
}
.rowcenter {
  display: flex;
  align-items: center;
}
</style>